package cn.rkylin.oms.system.supplier.controller;

import static cn.rkylin.apollo.enums.BusinessExceptionEnum.UPDATE_DATA;
import static cn.rkylin.oms.common.MediaType.APPLICATION_JSON_VALUE_UTF8;
import static org.springframework.http.HttpStatus.CREATED;
import static org.springframework.http.HttpStatus.OK;
import static org.springframework.web.bind.annotation.RequestMethod.DELETE;
import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.POST;
import static org.springframework.web.bind.annotation.RequestMethod.PUT;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

import cn.rkylin.core.controller.ApolloController;
import cn.rkylin.core.exception.BusinessException;
import cn.rkylin.oms.common.context.CurrentUser;
import cn.rkylin.oms.common.context.WebContextFactory;
import cn.rkylin.oms.common.domain.ClientSearchCondition;
import cn.rkylin.oms.common.dto.PagedData;
import cn.rkylin.oms.system.supplier.domain.SearchConditions;
import cn.rkylin.oms.system.supplier.domain.Supplier;
import cn.rkylin.oms.system.supplier.service.ISupplierService;

@RestController
@RequestMapping("/suppliers")
public class SupplierController extends ApolloController {

    @Autowired
    private ISupplierService supplierService;

    private static final Log logger = LogFactory.getLog(SupplierController.class);

    @RequestMapping(method = POST, consumes = APPLICATION_JSON_VALUE_UTF8)
    @ResponseStatus(CREATED)
    public Supplier create(@RequestBody Supplier supplier) throws Exception {
        checkEnterpriseId(supplier.getEnterpriseId(), "无权限创建该供货商！");
        if (StringUtils.isNotBlank(supplier.getCode())) {
            Supplier checkCode = new Supplier();
            checkCode.setEnterpriseId(supplier.getEnterpriseId());
            checkCode.setCode(supplier.getCode());
            List<Supplier> supplierList = supplierService.getSupplierList(supplier);
            if (supplierList.size() >= 1) {
                throw new BusinessException(UPDATE_DATA.getC(), "该供货商编码已存在");
            }
        } else {
            throw new BusinessException(UPDATE_DATA.getC(), "供货商编码为空");
        }
        return supplierService.create(supplier);
    }

    @RequestMapping(value = "/{id}", method = PUT, consumes = APPLICATION_JSON_VALUE_UTF8)
    @ResponseStatus(OK)
    public Supplier update(@PathVariable("id") String id, @RequestBody Supplier supplier) throws Exception {
        checkEnterpriseId(supplier.getEnterpriseId(), "无权限更新该供货商！");
        supplier.setId(id);
        return supplierService.update(supplier);
    }

    @RequestMapping(value = "/{id}", method = DELETE)
    @ResponseStatus(OK)
    public void delete(@PathVariable("id") String id, @RequestParam("enterprise") String enterpriseId) throws Exception {
        checkEnterpriseId(enterpriseId, "无权限删除该供货商！");
        supplierService.delete(id);
    }

    @RequestMapping(value = "/search", method = GET, produces = APPLICATION_JSON_VALUE_UTF8)
    public PagedData<Supplier> search(SearchConditions conditions, @PageableDefault Pageable pageable) throws Exception {
        CurrentUser currentUser = WebContextFactory.getWebContext().getCurrentUser();
        conditions.decode();
        List<String> currUserEnterpIds = new ArrayList<>(currentUser.getEnterpriseMap().keySet());
        conditions.setEnterpriseIds(currUserEnterpIds);
        return supplierService.search(pageable, conditions);
    }

    /**
     * Apollo检索方式（检索逻辑由前端确定）
     *
     * @param condition
     *            查询条件，该参数是{@link cn.rkylin.core.controller.vo.FormSelectVO}的数组
     * @param pageable
     *            分页信息
     *
     * @return 查询结果集
     */
    // TODO 将来使用自定义的converter将该参数conditions转换为对象
    @RequestMapping(value = "/client_search", method = RequestMethod.GET)
    public PagedData<Supplier> clientSearch(ClientSearchCondition condition, @PageableDefault Pageable pageable) throws Exception {
        CurrentUser currentUser = WebContextFactory.getWebContext().getCurrentUser();
        Map<String, Object> params = new HashMap<>();
        params.put("keyword", condition.getKeyword());
        params.put("conditions", condition.getSQLCondition());
        params.put("enterpriseIds", currentUser.getEnterpriseMap().keySet());
        return supplierService.search(pageable, params);
    }

    /**
     * 查询供应商列表
     * 
     * @return 结果Map
     * @throws Exception
     *             异常
     */
    @SuppressWarnings("rawtypes")
    @ResponseBody
    @RequestMapping(value = "/getSupplierList", method = RequestMethod.GET)
    public Map<String, Object> getSupplierList() throws Exception {
        // 用于返回值的JSON对象
        Map<String, Object> returnMap = new HashMap<String, Object>();
        try {
            // 设置企业Id
            CurrentUser currentUser = WebContextFactory.getWebContext().getCurrentUser();
            Iterator iterator = currentUser.getEnterpriseMap().keySet().iterator();
            String entId = (String) iterator.next();
            Supplier supplier = new Supplier();
            supplier.setEnterpriseId(entId);

            List<Supplier> supplierList = supplierService.getSupplierList(supplier);

            // 设置返回结果内容
            returnMap.put(JSON_RESULT, SUCCESS);
            returnMap.put(RETURN_DATA, supplierList);
        } catch (Exception ex) {
            logger.error(ex);
            returnMap.put(JSON_RESULT, FAILED);
            returnMap.put(JSON_MSG, ex.getMessage());
        }
        // 生成返回结果JSON串，null内容也需要返回
        return returnMap;
    }

    private void checkEnterpriseId(String enterpriseId, String message) throws BusinessException {
        CurrentUser currentUser = WebContextFactory.getWebContext().getCurrentUser();
        currentUser.checkEnterpriseId(enterpriseId, message);
    }

}
